//"use strict"
/**
 * Class: LNMPager
 */
function LNMPager(xpath)
{
	var t=this;
	this.element=$(xpath);
	this.element.addClass("LNMPager");
	this.scroller=$("<div class='LNMPager-scroller'></div>").appendTo(this.element);
	this.pages=0;
	this.objects=[];
    this.global_top_height=0;
    this.global_bottom_height=0;

	this.window_resize(0);
//	$(window).resize(function() { t.window_resize(1); });
	window.addEventListener("orientationchange",function() { t.window_resize(1); }, false);
	window.addEventListener("resize",function() { t.window_resize(1); }, false);


    if (window.cordova) {
		if (window.tinyHippos != undefined) {
			this.method="emulated";
		} else {
			this.method="phonegap";
		}
	} else {
		this.method="browser";
	}
	console.log("LNMPager(): method="+this.method);
}

/**
 * Method: set_global
 *
 * Parameters:
 *		options.object typeof Object					-
 *		options.top typeof Object, optional				-
 *		options.top.title typeof String, optional		-
 *		options.top.buttons typeof Array, optional		-
 *		options.top.buttons[i].name typeof String		-
 *		options.top.buttons[i].cssclass typeof String	-
 *		options.top.buttons[i].click typeof Function	-
 *		options.top.buttons[i].pos typeof Number		- position in percent, 0% - left, 100% - right
 *		options.top.after typeof HTML, optional			- optional
 *		options.top.cssclass typeof String, optional	-
 */
LNMPager.prototype.set_global=function(options)
{
	var topsize=0;
	var bottomsize=0;
	if (options["top"]) { topsize=this.set_global_section(options,"top");} else { $(".LNMPager-global-top",this.element).remove(); }
	if (options["bottom"]) { bottomsize=this.set_global_section(options,"bottom");} else { $(".LNMPager-global-bottom",this.element).remove(); }
	this.global_top_height=topsize ;
	this.global_bottom_height=bottomsize;
	this.window_resize();
}

/**
 * Method: set_global_section
 */
LNMPager.prototype.set_global_section=function(options,section)
{
	var t=this;
	$(".LNMPager-global-"+section,this.element).remove();
	var sdiv=$("<div class='LNMPager-global-section LNMPager-global-"+section+"'></div>")[(section=="top")?"prependTo":"appendTo"](this.element);
	this.publish_section_buttons(options,section,sdiv);
	return sdiv.height();
}

/**
 * Method: publish_section_buttons
 * Attributes: internal
 */
LNMPager.prototype.publish_section_buttons=function(options,section,sdiv)
{
	if ("title" in options[section]) {
		$("<div class='title'></div>").html(options[section].title).appendTo(sdiv);
	}
	if (options[section].cssclass) sdiv.addClass(options[section].cssclass);
	if (options[section].buttons) {
		/// let's apply button width and height to the standard, so that it could look good on any screen size:
		var M = this.width/480; /// this will be a ratio, if we consider 480 as a standard width
//		var lastKnob=null;
		for (var i=0; i<options[section].buttons.length; i++) {
			var button=options[section].buttons[i];
			var bdiv=$("<div class='button'></div>");
			if (button.cssclass) bdiv.addClass(button.cssclass);
			if (button.click) bdiv.bind("click",button.click);
			if (button.name) bdiv.html(button.name);
			bdiv.appendTo(sdiv);
			
//			bdiv.css({padding: M*14, 'padding-left': M*18, 'padding-right': M*18, 'border-radius':M*6});
			
			bdiv.css({"left":button.pos+"%","margin-left":-Math.round(bdiv.outerWidth()*(button.pos/100))/*, "top": 5+(section=='top' ? this.resize_top_shift : 0)*/});
//			lastKnob=bdiv;
		}
		/// refreshing the sdiv dimensions, so that it would fit the buttons heights:
//		sdiv.css({height:lastKnob.outerHeight()});
	}
	if (options[section].before) sdiv.prepend(options[section].before);
	if (options[section].after) sdiv.append(options[section].after);
    if (options[section].html) sdiv.html(options[section].html);
}

/**
 * Method: window_resize
 */
LNMPager.prototype.window_resize=function(do_resize)
{

    this.resize_top_shift = 0;
    this.resize_bottom_shift = 0;
    this.resize_page_shift = 0;

	var platform,version;
	if (window.device) {
    	platform = device.platform.toLowerCase();
    	version = device.version.split('.').map(function(a) { return parseFloat(a);});
	} else if (navigator.userAgent.match(/iPhone/)) {
		$("body").height(window.innerHeight);
		$("html").height(window.innerHeight);
	}

    switch (false && platform) {
        case 'ios':
            var ios_shift = 20;
            if (version[0]<7) {
                this.resize_page_shift = ios_shift;
            } else if (version[0]>=7) {
                this.resize_top_shift = ios_shift;
                //$(document.body).css({'margin-top':  ios_shift, 'overflow':'hidden'});
            }
            break;
        default:
            break;
    }

	this.width=this.element.width();
	this.height=this.element.height() - this.resize_page_shift-this.global_top_height-this.global_bottom_height ;//- this.resize_top_shift;

	console.log("LNMPager.window_resize() "+this.width+" x "+this.height);
	if (this.method=="phonegap") {
/*		if (device.platform=="iOS") {
			if (device.version<7) {
				this.height-=20;
			} else {
			}
		}*/
	}
	this.scroller.height(this.height);
	if (!do_resize) return;
	for (var i=0;i<this.pages;i++) {
		$(".LNMPager-page").eq(i).css({left:i*this.width,width:this.width,height:this.height});
	}
	this.scroller.css({"margin-left":-(this.pages-1)*this.width});


	// TODO place top/bottom section buttons
}

/**
 * Method: add_object
 * Parameters:
 *		object typeof Object
 */
LNMPager.prototype.add_object=function(object)
{
	var r=this.add(object.open());
	this.objects[r]=object;
	object.page_index=r;
	this.event("page_added");
	this.fire("set_url");
	return r;
}

/**
 * Method: add
 * Parameters:
 *		options.object typeof Object					-
 *		options.body typeof HTML						-
 *		options.top typeof Object, optional				-
 *		options.top.title typeof String, optional		-
 *		options.top.buttons typeof Array, optional		-
 *		options.top.buttons[i].name typeof String		-
 *		options.top.buttons[i].cssclass typeof String	-
 *		options.top.buttons[i].click typeof Function	-
 *		options.top.buttons[i].pos typeof Number		- position in percent, 0% - left, 100% - right
 *		options.top.after typeof HTML, optional			- optional
 *		options.top.cssclass typeof String, optional	-
 *		options.top.overlay typeof Boolean				-
 *		options.page_index typeof Integer				- optional
 *		options.fast typeof Boolean						- no animation
 *		options.extension typeof HTML, options			- sibling for LNMPager-main
 */
LNMPager.prototype.add=function(options)
{
	var t=this;
	if ("page_index" in options) {
		this.delete_extra_pages(options.page_index-1);
	}
	var pagediv=$("<div class='LNMPager-page'><div class='LNMPager-main'></div></div>").appendTo(this.scroller);
	if (options.extension) {
		var extensiondiv=$("<div class='LNMPager-extension'></div>");
		extensiondiv.html(options.extension);
		pagediv.append(extensiondiv);
	}
	if (options["top"]) this.add_section(options,pagediv,"top");
	if (options["bottom"]) this.add_section(options,pagediv,"bottom"); if (options["addclass"]) { pagediv.addClass(options["addclass"]); }; pagediv.css({left:this.pages*this.width,width:this.width,height:this.height});
	$(".LNMPager-main",pagediv).html(options.html);
	$(".LNMPager-main",pagediv).bind("scroll",function() { t.onscroll(this); });
	if (options.fast) {
		this.scroller.stop().css({"margin-left":-this.pages*this.width});
	} else {
		this.scroller.stop().animate({"margin-left":-this.pages*this.width});
	}
	this.objects[this.pages]=options.object||{};
	this.pages++;
    this.update_main_block_height();
	return this.pages-1;
}

/**
 * Method: update_main_size
 */
LNMPager.prototype.update_main_block_height=function(i)
{
	if (i===undefined) i=this.pages-1;
	var page=$(".LNMPager-page",this.scroller).eq(i);
	var topsize=0;
	var bottomsize=0;

//    $(".LNMPager-top",page).css({'padding-top': this.resize_top_shift});
	if ($(".LNMPager-top",page).length!=0 && $(".LNMPager-top.LNMPager-section-overlay",page).length==0) topsize=$(".LNMPager-top",page).height()+this.resize_top_shift;
	if ($(".LNMPager-bottom",page).length!=0 && $(".LNMPager-bottom.LNMPager-section-overlay",page).length==0) bottomsize=$(".LNMPager-bottom",page).height();
    $(".LNMPager-main",page).css({'padding-top': Math.round(topsize), bottom:Math.round(bottomsize)});
}

/**
 * Method: find_object
 *
 * Parameters:
 *		proto typeof Constructor		-
 */
LNMPager.prototype.find_object=function(proto)
{
    for (var i=0;i<this.objects.length;i++) {
		if (this.objects[i] && this.objects[i].constructor===proto) return i;
	}
	return undefined;
}

/**
 * Method: add_section
 */
LNMPager.prototype.add_section=function(options,pagediv,section)
{
	var t=this;
	$(".LNMPager-"+section,pagediv).remove();
	var sdiv=$("<div class='LNMPager-section LNMPager-"+section+"'></div>").appendTo(pagediv);
	if (options[section].overlay) sdiv.addClass("LNMPager-section-overlay");
	if (options[section].addclass) sdiv.addClass(options[section].addclass);
	this.publish_section_buttons(options,section,sdiv);
	return sdiv.height();
}

/**
 *
 */
LNMPager.prototype.replace_object=function(object)
{
	var h=object.open();
	h.page_index=this.pages-1;
	var r=this.add(h);
	this.objects[r]=object;
	object.page_index=r;
	return r;
}

/**
 * Method: back
 */
LNMPager.prototype.back=function(options) {
	this.go(this.pages-2, options);
}

/**
 * Method: go
 *
 * Parameters:
 *		index typeof Integer - page number
 *		options typeof Object
 *		options.fast typeof Boolean
 */
LNMPager.prototype.go=function(index,options) {
	if (!options) options={};
	console.log("LNMPager.go("+index+"), pages="+this.pages);
	if (this.pages<=index) return;
	var t=this;
	if (options.fast) {
		this.event("page_blur");
		this.scroller.stop().css({"margin-left":-index*this.width});
		this.delete_extra_pages(index);
		this.event("page_focus");
		this.fire("set_url");
	} else {
		this.event("page_blur");
		this.scroller.stop().animate({"margin-left":-index*this.width},undefined,undefined,function() {
			t.delete_extra_pages(index);
			t.event("page_focus");
			t.fire("set_url");
		});
	}
	if (options.after_func) options.after_func();
}

/**
 * Method: event
 */
LNMPager.prototype.event=function(name,arg1,arg2,arg3)
{
//	var page=this.pages-1;
	console.log(['LNMPager event:',name]);
	switch (name) {
		case "page_blur":
		case "page_focus":
		case "page_added":
//			if (this.objects[page]["on_"+name]) {
//				this.objects[page]["on_"+name](arg1,arg2,arg3);
//			}
			this.fire("on_"+name);
			break;
	}
}

/**
 * Method: set_title
 */
LNMPager.prototype.set_title=function(index,section,title) {

	var pagediv=$(".LNMPager-page",this.scroller).eq(index);
	$(".LNMPager-section.LNMPager-"+section+" .title",pagediv).html(title);
}

/**
 * Method: set_html
 */
LNMPager.prototype.set_html=function(index,html) {
	var pagediv=$(".LNMPager-page",this.scroller).eq(index);
	$(".LNMPager-main",pagediv).html(html);
}

/**
 * Method: set_extension
 */
LNMPager.prototype.set_extension=function(index,extension) {
	var pagediv=$(".LNMPager-page",this.scroller).eq(index);
	$(".LNMPager-extension",pagediv).html(extension);
}

/**
 * Method: get_page
 */
LNMPager.prototype.get_page=function(index) {
	var i = (index != undefined) ? index : (this.pages-1);
	return pagediv=$(".LNMPager-page",this.scroller).eq(i);
}

/**
 * Method: get_html
 */
LNMPager.prototype.get_html=function(index) {

	//var pagediv=$(".LNMPager-page",this.scroller).eq(index||(this.pages-1));
	return $(".LNMPager-main",this.get_page(index));
}

/**
 * Method: get_full_page_html
 */
LNMPager.prototype.get_full_page_html=function(index) {

	var pagediv=$(".LNMPager-page",this.scroller).eq(index);
	return pagediv;
}

/**
 * Method: delete_extra_pages
 */
LNMPager.prototype.delete_extra_pages=function(index) {
	this.pages=index+1;
	while (this.objects.length>index+1) this.objects.pop();
	var arr=$(">.LNMPager-page",this.scroller);
	for (var i=index+1;i<arr.length;i++) $(arr[i]).remove();
}

/**
 * Method: fire
 */
LNMPager.prototype.fire=function(func,object,object2) {
/*	if (!this.objects[this.pages-1][func]) {
		console.log("LNMPager.fire() - page "+(this.pages-1)+" does not have "+func+"() method");
		return;
	}
	this.objects[this.pages-1][func](object,object2);*/
	this.fire_on_page(this.pages-1,func,object,object2);
}

/**
 * Method: fire_on_page
 */
LNMPager.prototype.fire_on_page=function(page,func,object,object2) {
	if (!this.objects[page][func]) {
		console.log("LNMPager.fire() - page "+page+" does not have "+func+"() method");
		return;
	}
	this.objects[page][func](object,object2);
}

/**
 * Method: onscroll
 */
LNMPager.prototype.onscroll=function(div)
{

}

/**
 * Method: get_object
 */
LNMPager.prototype.get_object=function(index)
{
    console.log(['get object', this.objects, index]);
    return this.objects[typeof index=='undefined' ? this.page_index : index];
}


/**
 * Method: toggle_sider
 *
 *  Открывает боковое меню
 */
LNMPager.prototype.toggle_sider=function()
{
    this.sider.toggleClass('active');
}

/**
 * Method: init_sider
 *
 *	Инициализирует боковое меню
 * 
 */
LNMPager.prototype.init_sider=function(html,init_actions){
    this.sider.html(html).addClass('initialized');
	this.element.addClass('with_sider');
	if(init_actions) init_actions(this.sider);
}
